<?php
/**
 * Created by PhpStorm.
 * User: linhui
 * Date: 2016/12/13
 * Time: 21:19
 */

namespace Admin\Controller;

use Common\Lib\Qiniu;
use Common\Model\SmsLogsModel;
use Think\Upload;

class PublicController extends BasicController
{
    /**
     *非法路由页面
     */
    public function _empty()
    {
        header("HTTP/1.0 404 Not Found");
        $this -> display("Public:denied");
    }

    public function denied()
    {
        list($menus, $bread_crumb) = $this->initMenu();

        $this->assign('menuList', $menus);
        $this->assign('bread_crumb', $bread_crumb);
        $this->display();
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        $upload = new Upload();
        foreach ($_FILES as $key => $vo) {
            $res = $upload->uploadOne ($vo);
            if($res){
                $url = $upload->rootPath.$res['savepath'].$res['savename'];
                $qn_response = Qiniu::QiniuUpload($url, $res['savename']);
                if($qn_response['status']) {
                    unlink($url);
                    $this->responseAjax('上传成功', true, ['url'=>C('QINIU.domain').$qn_response['url']]);
                } else {
                    $this->responseAjax($qn_response['msg']);
                }

            } else {
                $this->responseAjax($upload->getError());
            }
            $this->responseAjax('上传失败');
        }
    }


    /**
     *登录
     */
    public function login()
    {
        if(IS_POST){
            $model = D('user');
            $user_login = I('user_login');
            $user_pass = I('user_pass');
            $code = I('code');
            $token = I('token');
            $map = array('user_login'=>$user_login);
            $user_info = $model->where($map)->find();
            if((new SmsLogsModel())->verify($user_info['mobile'], $code) != 0){
                $resp = array('msg'=>'验证码错误', 'status'=>false, 'errbtn'=>'code');
            } else if(!$user_info){
                $resp = array('msg'=>'账号不存在', 'status'=>false, 'errbtn'=>'user_login');
            }else if($user_info['user_pass'] == sp_password($user_pass)){
                $user_info['role_ids'] = M('AdminRole')->where(array('admin_id'=>$user_info['user_id']))->getField('role_id', true);
                session('user', $user_info);
                //保存登录记录
                $model->where($map)->save(array(
                    'login_time'=>time(),
                    'login_ip'=>$_SERVER['REMOTE_ADDR'],
                ));
                $resp = array('msg'=>'登录成功', 'status'=>true, 'redirectUrl'=>U('Index/index'));
            } else {
                $resp = array('msg'=>'账号密码错误', 'status'=>false, 'errbtn'=>'user_pass');
            }

            $this->ajaxReturn($resp, 'json');
        } else {
            if(getLoginInfo()){
                $this->redirect('Index/index');
            } else{
                $this->display();
            }
        }

    }

    /**
     * 登录获取验证码
     */
    public function getCodeByLogin()
    {
        $data = I('request.');
        if($data['user_login']) {
            $user = M('User')->where(['user_login'=>$data['user_login']])->field('user_id, mobile, user_login')->find();
            if(!$user['mobile']) {
                $this->responseAjax('此用户无法登录');
            }

            $sms = new SmsLogsModel();
            $response = $sms->send($user['mobile'], 'login', $user['user_id']);
            if($response['status']) {
                $this->responseAjax($response['info'], true);
            } else {
                $this->responseAjax($response['info']);
            }
        } else {
            $this->responseAjax('用户不存在');
        }
    }
    /**
     * 获取验证码
     */
    public function getCode()
    {
        $data = I('request.');
        if($data['mobile']) {
            $sms = new SmsLogsModel();
            $response = $sms->send($data['mobile'], $data['action']);
            if($response['status']) {
                $this->responseAjax($response['info'], true);
            } else {
                $this->responseAjax($response['info'], false, ['errorCode'=>$response['error']]);
            }
        } else {
            $this->responseAjax('用户不存在');
        }
    }

    /**
     * 上传文件列表
     */
    public function uploadFiles()
    {
        $extension = I('ext', '', 'strval');
        $markStart = I('mark');
        list($list, $mark) = \Common\Lib\Qiniu::_list($extension, 100, $markStart);
        $this->assign('list', $list);
        $this->assign('mark', $mark);
        $this->assign('markStart', $markStart);
        $this->assign('qiniu', C('QINIU'));
        $this->display();
    }

    /**
     * 获取七牛token
     */
    public function qiniuToken()
    {
        $this->responseAjax(\Common\Lib\Qiniu::getToken(), true);
    }

    public function loginOut()
    {
        session(null);
        $this->redirect('login');
    }

    /**
     *验证码
     */
    public function verify()
    {
        $config = array(
            'useCurve'=>false,
            'length'=>4,
        );
        $token = I('token');
        $Verify = new \Think\Verify($config);
        $Verify->entry($token);
    }

    /**
     * 检查验证码
     */
    public function ajaxVerify()
    {
        $token = I('token');
        $code = I('code', '', 'strtoupper');
        if($this->checkVerify($code, $token)){
            $resp = array('status'=>true);
        }else{
            $resp = array('status'=>false, 'msg'=>'验证码错误',  'errbtn'=>'code');
        }
        $this->ajaxReturn($resp, 'json');
    }

    /**
     * 验证码验证
     * @param $code
     * @param $token
     * @return bool
     */
    public function checkVerify($code, $token){
        $Verify = new \Think\Verify();
        $this->seKey = $Verify->seKey;
        $verify_token = $this->authcode($this->seKey).$token;
        return session($verify_token . '.verify_code') == $this->authcode(strtoupper($code)) ? true : false;
    }

    /**
     * Thinkphp 验证码加密
     * @param $str
     * @return string
     */
    public function authcode($str)
    {
        $key = substr(md5($this->seKey), 5, 8);
        $str = substr(md5($str), 8, 10);
        return md5($key . $str);
    }

    /**
     *获取token
     */
    public function token()
    {
        $this->ajaxReturn(array('status'=>true, 'data'=>token()));
    }

    /**
     *选择图标
     */
    public function icon()
    {
        $this->display();
    }


    /**
     *清除缓存文件
     */
    public function clean()
    {
        delFile(APP_PATH.DIRECTORY_SEPARATOR.'Runtime');
        $this->responseAjax('清除成功', true);
    }

}